﻿@using WishlistUtilities;
@{
	PageData["Title"] = "Create List";

	WebSecurity.RequireAuthenticatedUser();
    Freemium.RequireFeatureEnabledForCurrentPage("Create Lists");             

	var db = Database.Open("wishlistdb");
}
<h1>Create List</h1>
@{
    var errorMessage = "";

	if (IsPost) {
        //Create the list, ensuring that there are no duplicates in the table for that user
		if (!Request["listName"].IsEmpty() && !Request["listDescription"].IsEmpty()) {
			var slug = SlugUtility.CreateSlug(Request["listName"]);
            //Replace slug character with SQL wildcard _
            var sqlSluggedListName = slug.Replace(SlugUtility.SLUGREPLACEMENTCHAR, '_');
            var duplicateList = db.QueryValue("SELECT COUNT(*) FROM List WHERE Name LIKE @0 AND WishlistUserID = @1", 
                    sqlSluggedListName, WebSecurity.CurrentUserId) > 0;
			if (!duplicateList) {
                try {
                    db.Execute("INSERT INTO List (Name, Description, Slug, WishlistUserId) VALUES (@0, @1, @2, @3)",
                        Request["listName"], Request["listDescription"], slug, WebSecurity.CurrentUserId);
                } catch (Exception) {
                    Response.Redirect("~/Shared/Errors/Error");
                }
                Response.Redirect("~/ManageLists");
			} else {
				errorMessage = "<li>You already have a list with this name!</li>";
			}
		} else {
			errorMessage = "<li>List name or description cannot be empty.</li>";
		}
	}
    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}
<div>
    <fieldset>
        <form id="validateForm" method="post" action="">
	        @RenderPage("~/Shared/_InputFormField.cshtml", 
                new { labelName = "listName", labelDisplay = "Name:", maxLength = 100, required = true})
	        @RenderPage("~/Shared/_InputFormField.cshtml",
                new { labelName = "listDescription", labelDisplay = "Description:", maxLength = 500, required = true})
	        <div class="submit-group">
		        <input type="submit" value="Create" onclick="javascript:$('#validateForm').validate()" />
	        </div>
        </form>
    </fieldset>
</div>